<template>
  <div class="pest-detection-container">
    <!-- 左侧面板 -->
    <div class="left-panel">
      <!-- 图片上传区域 -->
      <div class="upload-card">
        <div class="card-header">
          <i class="el-icon-picture-outline"></i>
          <span>校园昆虫检测</span>
          <el-tooltip content="点击图片区域可重新上传" placement="top">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </div>
        <div class="upload-area" @click="handleUploadClick">
          <img v-if="imageUrl" :src="imageUrl" class="uploaded-image" />
          <div v-else class="upload-placeholder">
            <i class="el-icon-upload"></i>
            <div>点击上传昆虫图片</div>
          </div>
          <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleFileChange" />
        </div>
      </div>

      <!-- 检测结果区域 -->
      <div class="result-card">
        <div class="card-header">
          <i class="el-icon-document"></i>
          <span>检测结果</span>
          <el-tag v-if="detectionTime" size="mini" type="info">
            检测时间: {{ detectionTime }}
          </el-tag>
        </div>
        <el-table :data="detectionResults" stripe style="width: 100%" height="400px" v-loading="loading">
          <el-table-column prop="accuracy" label="置信度" width="120" sortable>
            <template slot-scope="{ row }">
              <div style="display: flex; align-items: center;">
                <el-progress :percentage="row.accuracy" :color="getProgressColor(row.accuracy)" :show-text="false"
                  :stroke-width="12" style="flex: 1; margin-right: 10px;" />
                <span>{{ row.accuracy }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="分类" width="150">
            <template slot-scope="{ row }">
              <el-tag :type="row.danger ? 'danger' : 'success'" size="small">
                {{ row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="昆虫名称" width="150">
            <template slot-scope="{ row }">
              <span :class="{ 'danger-text': row.danger }">
                {{ row.name }}
                <el-tag v-if="row.danger" size="mini" type="danger">害虫</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="desc" label="昆虫特征" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span v-if="row.desc">{{ row.desc }}</span>
              <span v-else class="no-desc">暂无描述</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="{ row, $index }">
              <el-button type="text" size="small" @click.stop="viewWiki(row)">
                详情
              </el-button>
              <el-button type="text" size="small" @click.stop="confirmDelete(row, $index)" style="color: red">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 右侧面板 -->
    <div class="right-panel">
      <!-- 搜索区域 -->
      <div class="search-card">
        <div class="card-header">
          <i class="el-icon-search"></i>
          <span>昆虫搜索</span>
        </div>
        <div class="search-box">
          <el-input v-model="searchQuery" placeholder="输入害虫名称搜索" clearable @keyup.enter.native="handleSearch"
            @clear="handleClearHistory">
            <i slot="prefix" class="el-icon-search"></i>
          </el-input>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch" :loading="searchLoading">
            搜索
          </el-button>
        </div>
      </div>

      <!-- 历史记录区域 -->
      <div class="history-card">
        <div class="card-header">
          <i class="el-icon-time"></i>
          <span>检测历史</span>
          <el-button type="text" size="mini" @click="clearHistory" :disabled="historyData.length === 0">
            清空历史
          </el-button>
        </div>
        <el-table :data="historyData" height="100%" style="width: 100%" empty-text="暂无检测历史"
          @row-click="handleHistoryClick">
          <el-table-column prop="time" label="检测时间" width="180">
            <template slot-scope="{ row }">
              <el-tooltip :content="row.time" placement="top">
                <span>{{ formatTime(row.time) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="result" label="检测结果">
            <template slot-scope="{ row }">
              <div class="result-summary">
                <span v-for="(item, index) in row.results" :key="index">
                  <span :class="{ 'danger-text': item.danger }">{{ item.name }}</span>
                  <span v-if="index < row.results.length - 1">, </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click.stop="viewHistoryDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 上传对话框 -->
    <el-dialog :visible.sync="uploadDialogVisible" title="上传昆虫图片" width="500px" :close-on-click-modal="false"
      :before-close="handleBeforeClose">
      <el-upload class="upload-dialog" drag action="#" :auto-upload="false" :show-file-list="false"
        :on-change="handleDialogUpload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          支持JPG/PNG格式，大小不超过5MB
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpload" :disabled="!selectedFile" :loading="uploadLoading">
          确认上传
        </el-button>
      </div>
    </el-dialog>

    <!--详情 -->
    <el-dialog :visible.sync="insectDetail" title="百科" width="800px" :close-on-click-modal="false" center>
      <div class="baike-content" style="max-height: 600px; overflow-y: auto; padding: 24px;">
        <h3 style="font-weight:bold; font-size:20px; margin-bottom:16px;">{{ baikeDetail.title }}</h3>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.summary }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">基本信息</h4>
        <table style="width:100%; font-size:14px; margin-bottom:18px; border-collapse:collapse;">
          <tr v-for="(row, idx) in baikeDetail.basicInfo" :key="idx">
            <td style="width:80px; color:#888;">{{ row[0] }}</td>
            <td>{{ row[1] }}</td>
            <td style="width:80px; color:#888;" v-if="row[2]">{{ row[2] }}</td>
            <td v-if="row[3]">{{ row[3] }}</td>
          </tr>
        </table>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">形态特征</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.feature }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">生活习性</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.habit }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">分布范围</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.distribution }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">繁殖方式</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.reproduction }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">防治方法</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.control }}
        </div>
      </div>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="deleteDialogVisible" width="300px" :close-on-click-modal="false">
      <span>确定要删除该条数据吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDelete">取消</el-button>
        <el-button type="primary" @click="handleDelete">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PestDetection',
  data() {
    return {
      imageUrl: '',
      searchQuery: '',
      loading: false,
      searchLoading: false,
      uploadDialogVisible: false,
      insectDetail: false,
      selectedFile: null,
      detectionTime: this.getCurrentDateTime(),
      detectionResults: [
        { accuracy: 94.35, type: '动物-节肢动物', name: '红蜘蛛', danger: true, desc: '红蜘蛛，是螨纲目叶螨科害虫，主要危害植物叶片，吸食汁液导致叶片发黄脱落。' },
        { accuracy: 75.10, type: '动物-节肢动物', name: '螨', danger: false, desc: '螨类是一类小型节肢动物，部分种类对植物有益，能捕食其他害虫。' },
        { accuracy: 55.36, type: '动物-节肢动物', name: '姬螨', danger: false, desc: '姬螨（comb-footed spider）是一类无害的蜘蛛，常生活在植物上捕食小型昆虫。' },
        { accuracy: 34.08, type: '动物-昆虫类', name: '螨子硬螨', danger: false, desc: '螨子硬螨体狭长，多数种类无害，少数可能对植物造成轻微危害。' },
        { accuracy: 11.76, type: '动物-节肢动物', name: '螨虫', danger: true, desc: '螨虫，寄菊目螨兔科害虫，可导致植物叶片卷曲变形，传播植物病毒。' },
      ],
      historyData: [
        {
          time: this.getCurrentDateTime(),
          results: [
            { name: '红蜘蛛', danger: true },
            { name: '螨', danger: false },
            { name: '姬螨', danger: false },
            { name: '螨子硬螨', danger: false },
            { name: '螨虫', danger: true }
          ]
        },
        {
          time: this.getPastDateTime(1), // 1天前
          results: [
            { name: '蚜虫', danger: true },
            { name: '瓢虫', danger: false }
          ]
        },
        {
          time: this.getPastDateTime(2), // 2天前
          results: [
            { name: '白粉虱', danger: true }
          ]
        }
      ],
      historyData_pass: [
        {
          time: this.getCurrentDateTime(),
          results: [
            { name: '红蜘蛛', danger: true },
            { name: '螨', danger: false },
            { name: '姬螨', danger: false },
            { name: '螨子硬螨', danger: false },
            { name: '螨虫', danger: true }
          ]
        },
        {
          time: this.getPastDateTime(1), // 1天前
          results: [
            { name: '蚜虫', danger: true },
            { name: '瓢虫', danger: false }
          ]
        },
        {
          time: this.getPastDateTime(2), // 2天前
          results: [
            { name: '白粉虱', danger: true }
          ]
        }
      ],
      baikeMap: {
        '红蜘蛛': {
          title: '红蜘蛛百科',
          summary: '红蜘蛛，是螨纲目叶螨科害虫，体型微小，体表有细密纹理，主要危害植物叶片，吸食汁液导致叶片发黄脱落。红蜘蛛繁殖力强，适应性广，常见于温室、果园、花卉等植物上。防治方法包括药剂喷洒、生物防治、环境调控等。',
          basicInfo: [
            ['别名', '红叶螨', '纲', '蛛形纲'],
            ['中文学名', '红蜘蛛', '亚纲', '广腹亚纲'],
            ['拉丁学名', 'Tetranychus cinnabarinus', '目', '蜱螨目'],
            ['界', '动物界', '科', '叶螨科'],
            ['门', '节肢动物门', '属', '宝螨属'],
            ['亚门', '蛛形亚门', '分布', '亚洲多种作物'],
            ['寿命', '1年13代']
          ],
          feature: '红蜘蛛成虫体长0.42～0.52毫米，体色变化大，体表有细密纹理，体背隆起，有刚毛，雌虫体色偏红，雄虫体色偏黄。卵圆形，半透明，孵化后幼虫体色浅黄。',
          habit: '喜群居在植物叶片背面，善于繁殖，雌虫一生可产卵百余粒，常见于温室、果园、花卉等植物上。高温干燥环境易爆发。',
          distribution: '红蜘蛛广泛分布于亚洲、欧洲、美洲等地，主要危害蔬菜、果树、花卉等多种作物。',
          reproduction: '红蜘蛛一年可繁殖13代，卵期约4天，幼虫期约14天，成虫期约36天。高温干燥时繁殖更快。',
          control: '主要采用药剂喷洒、生物防治、环境调控等综合措施。常用药剂有阿维菌素、哒螨灵等。'
        },
        '螨': {
          title: '螨百科',
          summary: '螨类是一类小型节肢动物，部分种类对植物有益，能捕食其他害虫。',
          basicInfo: [
            ['纲', '蛛形纲', '科', '螨科'],
            ['门', '节肢动物门', '分布', '全球广泛分布']
          ],
          feature: '体型微小，种类繁多，部分螨类体表有刚毛。',
          habit: '部分螨类群居，部分独居，生活习性多样。',
          distribution: '全球广泛分布，常见于土壤、植物、动物体表。',
          reproduction: '多为卵生，繁殖力强。',
          control: '有益螨类可用于生物防治，有害螨类需药剂防治。'
        },
        '姬螨': {
          title: '姬螨百科',
          summary: '姬螨（comb-footed spider）是一类无害的蜘蛛，常生活在植物上捕食小型昆虫。',
          basicInfo: [
            ['纲', '蛛形纲', '科', '姬螨科'],
            ['门', '节肢动物门', '分布', '植物叶片']
          ],
          feature: '体型小，足部有梳状刚毛。',
          habit: '常见于植物叶片，捕食小型昆虫。',
          distribution: '广泛分布于植物叶片。',
          reproduction: '卵生，繁殖力一般。',
          control: '无害，无需防治。'
        },
        '螨子硬螨': {
          title: '螨子硬螨百科',
          summary: '螨子硬螨体狭长，多数种类无害，少数可能对植物造成轻微危害。',
          basicInfo: [
            ['纲', '蛛形纲', '科', '硬螨科'],
            ['门', '节肢动物门', '分布', '土壤、植物']
          ],
          feature: '体狭长，体表坚硬。',
          habit: '多生活于土壤或植物表面。',
          distribution: '土壤、植物广泛分布。',
          reproduction: '卵生。',
          control: '多数无害，无需防治。'
        },
        '螨虫': {
          title: '螨虫百科',
          summary: '螨虫，寄菊目螨兔科害虫，可导致植物叶片卷曲变形，传播植物病毒。',
          basicInfo: [
            ['纲', '蛛形纲', '科', '螨兔科'],
            ['门', '节肢动物门', '分布', '植物叶片']
          ],
          feature: '体型微小，体色浅黄。',
          habit: '寄生于植物叶片，吸食汁液。',
          distribution: '植物叶片广泛分布。',
          reproduction: '卵生，繁殖力强。',
          control: '药剂防治，环境调控。'
        }
      },
      baikeDetail: {
        title: '', summary: '', basicInfo: [], feature: '', habit: '', distribution: '', reproduction: '', control: ''
      },
      deleteDialogVisible: false,
      deleteRow: null,
      deleteIndex: null,
    }
  },
  computed: {
    hasDetectionResults() {
      return this.detectionResults.length > 0
    }
  },
  methods: {
    // 获取当前日期时间 (YYYY-MM-DD HH:mm:ss)
    getCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 获取过去某天的日期时间 (n天前)
    getPastDateTime(days) {
      const date = new Date();
      date.setDate(date.getDate() - days);

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 格式化时间为MM-DD HH:mm
    formatTime(timeString) {
      const date = new Date(timeString);
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${month}-${day} ${hours}:${minutes}`;
    },

    handleUploadClick() {
      this.uploadDialogVisible = true;
    },

    handleFileChange(e) {
      const file = e.target.files[0];
      if (file) {
        this.previewImage(file);
      }
    },

    handleDialogUpload(file) {
      this.selectedFile = file;
      this.previewImage(file.raw);
    },

    previewImage(file) {
      if (!file.type.match('image.*')) {
        this.$message.error('请选择图片文件');
        return;
      }

      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('图片大小不能超过5MB');
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        this.imageUrl = e.target.result;
      };
      reader.readAsDataURL(file);
    },

    confirmUpload() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择图片');
        return;
      }

      this.loading = true;
      this.uploadDialogVisible = false;

      // 模拟上传和检测过程
      setTimeout(() => {
        this.detectionTime = this.getCurrentDateTime();
        // 添加到历史记录
        this.historyData.unshift({
          time: this.detectionTime,
          results: this.detectionResults.map(item => ({
            name: item.name,
            danger: item.danger
          }))
        });
        this.loading = false;
        this.$message.success('检测完成');
      }, 1500);
    },

    handleSearch() {
      if (!this.searchQuery.trim()) {
        this.$message.warning('请输入搜索内容');
        return;
      }

      this.searchLoading = true;
      // 模拟搜索
      setTimeout(() => {
        this.searchLoading = false;
        // this.$message.success(`搜索: ${this.searchQuery}`);
        this.historyData = this.historyData.filter(item =>
          item.results.some(result => result.name.includes(this.searchQuery))
        );
      }, 800);
    },

    handleClearHistory() {

      this.historyData = this.historyData_pass;
    },
    viewWiki(row) {
      // 动态切换百科内容
      this.baikeDetail = this.baikeMap[row.name] || {
        title: row.name + '百科',
        summary: row.desc || '暂无百科内容',
        basicInfo: [],
        feature: '',
        habit: '',
        distribution: '',
        reproduction: '',
        control: ''
      };
      this.insectDetail = true;
    },

    viewHistoryDetail(row) {
      this.$message.info(`查看历史详情: ${row.time}`);
    },

    clearHistory() {
      this.$confirm('确定要清空所有检测历史吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.historyData = [];
        this.$message.success('历史记录已清空');
      }).catch(() => { });
    },

    confirmDelete(row, index) {
      this.deleteDialogVisible = true;
      this.deleteRow = row;
      this.deleteIndex = index;
    },
    handleDelete() {
      this.detectionResults.splice(this.deleteIndex, 1);
      this.deleteDialogVisible = false;
      this.deleteRow = null;
      this.deleteIndex = null;
      this.$message.success('删除成功');
    },
    cancelDelete() {
      this.deleteDialogVisible = false;
      this.deleteRow = null;
      this.deleteIndex = null;
    },

    getProgressColor(percentage) {
      if (percentage > 90) return '#67C23A';
      if (percentage > 70) return '#409EFF';
      if (percentage > 50) return '#E6A23C';
      return '#F56C6C';
    },

    handleRowClick(row) {
      this.viewWiki(row);
    },

    handleHistoryClick(row) {
      this.viewHistoryDetail(row);
    }
  }
}
</script>

<style>
.pest-detection-container {
  display: flex;
  height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f5f7fa;
  position: relative;
  gap: 20px;
}

.pest-detection-container .left-panel {
  flex: 0 0 60%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.pest-detection-container .right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.pest-detection-container .card-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f8f9fa;
  border-radius: 4px 4px 0 0;
  font-weight: 500;
  color: #333;
}

.pest-detection-container .card-header i {
  margin-right: 8px;
  font-size: 16px;
}

.pest-detection-container .card-header .el-tag,
.pest-detection-container .card-header .el-button {
  margin-left: auto;
}

.pest-detection-container .upload-card,
.pest-detection-container .result-card,
.pest-detection-container .search-card,
.pest-detection-container .history-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.pest-detection-container .upload-card .upload-area {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
  min-height: 300px;
}

.pest-detection-container .upload-card .upload-area:hover {
  background-color: #f5f7fa;
}

.pest-detection-container .upload-card .uploaded-image {
  max-width: 100%;
  max-height: 300px;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pest-detection-container .upload-card .upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.pest-detection-container .upload-card .upload-placeholder i {
  font-size: 48px;
  margin-bottom: 16px;
}

.pest-detection-container .result-card {
  flex: 1;
}

.pest-detection-container .result-card .el-table {
  flex: 1;
}

.pest-detection-container .result-card .danger-text {
  color: #f56c6c;
  font-weight: 500;
}

.pest-detection-container .result-card .no-desc {
  color: #c0c4cc;
  font-style: italic;
}

.pest-detection-container .result-card .el-progress {
  display: inline-block;
  width: 60px;
  margin-right: 8px;
  vertical-align: middle;
}

.pest-detection-container .search-card .search-box {
  padding: 20px;
  display: flex;
  gap: 10px;
}

.pest-detection-container .search-card .search-box .el-input {
  flex: 1;
}

.pest-detection-container .history-card {
  flex: 1;
}

.pest-detection-container .history-card .el-table {
  flex: 1;
}

.pest-detection-container .history-card .result-summary {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pest-detection-container .history-card .danger-text {
  color: #f56c6c;
}

.upload-dialog {
  text-align: center;
  padding: 20px;
}

.upload-dialog .el-upload-dragger {
  padding: 40px 20px;
}

.upload-dialog .el-upload__tip {
  margin-top: 10px;
  color: #909399;
}

@media (max-width: 992px) {
  .pest-detection-container {
    flex-direction: column;
    height: auto;
  }

  .pest-detection-container .left-panel,
  .pest-detection-container .right-panel {
    flex: 1 1 100%;
  }
}
</style>
